﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace FileBrowser
{
    public partial class MainForm : Form
    {
        private string currentDirectory;

        public MainForm()
        {
            InitializeComponent();
            InitializeFileBrowser();
            InitializeListView();
        }

        private void InitializeFileBrowser()
        {
            // 设置TreeView属性
            treeView1.BeginUpdate();
            treeView1.Nodes.Clear();

            // 添加我的电脑节点
            TreeNode rootNode = new TreeNode("我的电脑");
            treeView1.Nodes.Add(rootNode);

            // 添加所有驱动器
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                TreeNode driveNode = new TreeNode(drive.Name);
                driveNode.Tag = drive.RootDirectory.FullName;
                rootNode.Nodes.Add(driveNode);

                // 添加一级子目录
                AddDirectories(driveNode, drive.RootDirectory.FullName);
            }

            treeView1.EndUpdate();
            treeView1.ExpandAll();
        }

        private void AddDirectories(TreeNode parentNode, string path)
        {
            try
            {
                foreach (string directory in Directory.GetDirectories(path))
                {
                    TreeNode dirNode = new TreeNode(Path.GetFileName(directory));
                    dirNode.Tag = directory;
                    parentNode.Nodes.Add(dirNode);
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 忽略无权限访问的目录
            }
        }

        private void InitializeListView()
        {
            listView1.View = View.Details;
            listView1.Columns.Add("名称", 200);
            listView1.Columns.Add("类型", 100);
            listView1.Columns.Add("修改日期", 150);
            listView1.Columns.Add("大小", 100);
            listView1.FullRowSelect = true;
            listView1.DoubleClick += ListView1_DoubleClick;
        }

        private void LoadDirectory(string path)
        {
            currentDirectory = path;
            listView1.Items.Clear();

            try
            {
                // 添加上级目录项
                if (Directory.GetParent(path) != null)
                {
                    ListViewItem parentItem = new ListViewItem("..");
                    parentItem.SubItems.Add("文件夹");
                    parentItem.SubItems.Add("");
                    parentItem.SubItems.Add("");
                    parentItem.Tag = "PARENT";
                    listView1.Items.Add(parentItem);
                }

                // 添加子目录
                foreach (string directory in Directory.GetDirectories(path))
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(directory);
                    ListViewItem item = new ListViewItem(dirInfo.Name);
                    item.SubItems.Add("文件夹");
                    item.SubItems.Add(dirInfo.LastWriteTime.ToString());
                    item.SubItems.Add("");
                    item.Tag = dirInfo.FullName;
                    listView1.Items.Add(item);
                }

                // 添加文件
                foreach (string file in Directory.GetFiles(path))
                {
                    FileInfo fileInfo = new FileInfo(file);
                    ListViewItem item = new ListViewItem(fileInfo.Name);
                    item.SubItems.Add(fileInfo.Extension + " 文件");
                    item.SubItems.Add(fileInfo.LastWriteTime.ToString());
                    item.SubItems.Add(fileInfo.Length.ToString("N0"));
                    item.Tag = fileInfo.FullName;
                    listView1.Items.Add(item);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                MessageBox.Show($"无法访问目录: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                LoadDirectory(e.Node.Tag.ToString());
            }
        }

        private void ListView1_DoubleClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;

            string selectedPath = listView1.SelectedItems[0].Tag.ToString();

            if (listView1.SelectedItems[0].Text == "..")
            {
                // 处理上级目录
                string parentPath = Directory.GetParent(currentDirectory).FullName;
                LoadDirectory(parentPath);

                // 更新TreeView选择
                SelectTreeNodeByPath(parentPath);
            }
            else if (Directory.Exists(selectedPath))
            {
                // 处理目录
                LoadDirectory(selectedPath);

                // 更新TreeView选择
                SelectTreeNodeByPath(selectedPath);
            }
            else if (File.Exists(selectedPath) && Path.GetExtension(selectedPath).ToLower() == ".xml")
            {
                // 处理XML文件
                ShowXmlContent(selectedPath);
            }
        }

        private void SelectTreeNodeByPath(string path)
        {
            TreeNode foundNode = FindTreeNodeByPath(treeView1.Nodes, path);
            if (foundNode != null)
            {
                treeView1.SelectedNode = foundNode;
                treeView1.Focus();
            }
        }

        private TreeNode FindTreeNodeByPath(TreeNodeCollection nodes, string path)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Tag != null && node.Tag.ToString().Equals(path, StringComparison.OrdinalIgnoreCase))
                {
                    return node;
                }

                TreeNode foundNode = FindTreeNodeByPath(node.Nodes, path);
                if (foundNode != null)
                {
                    return foundNode;
                }
            }
            return null;
        }

        private void ShowXmlContent(string xmlFilePath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlFilePath);

                XmlViewerForm viewerForm = new XmlViewerForm();
                viewerForm.LoadXml(xmlDoc);
                viewerForm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法读取XML文件: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void viewMenuItems_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
            if (menuItem == null) return;

            listView1.View = (View)Enum.Parse(typeof(View), menuItem.Tag.ToString());
        }

        private void toolStripButtonBack_Click(object sender, EventArgs e)
        {
            // 实现后退功能
        }

        private void toolStripButtonForward_Click(object sender, EventArgs e)
        {
            // 实现前进功能
        }

        private void toolStripButtonUp_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(currentDirectory) && Directory.GetParent(currentDirectory) != null)
            {
                string parentPath = Directory.GetParent(currentDirectory).FullName;
                LoadDirectory(parentPath);
                SelectTreeNodeByPath(parentPath);
            }
        }

        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(currentDirectory))
            {
                LoadDirectory(currentDirectory);
            }
        }
    }
}